// ==UserScript==
// @name       		LeekWars : LeeKikiMeter
// @description  	Ce script affiche un résumé des combats de leekwars
// @match      		http://leekwars.com/report/
// @author			Elzéar
// @grant			none
// ==/UserScript==

var s = document.createElement('script');
s.src = chrome.extension.getURL('chart.js');

var colorTeam1 = '#780000';
var colorTeam2 = '#035800';

function colorLuminance(hex, lum) {
	// validate hex string
	hex = String(hex).replace(/[^0-9a-f]/gi, '');
	if (hex.length < 6) {
		hex = hex[0]+hex[0]+hex[1]+hex[1]+hex[2]+hex[2];
	}
	lum = lum || 0;
	// convert to decimal and change luminosity
	var rgb = "#", c, i;
	for (i = 0; i < 3; i++) {
		c = parseInt(hex.substr(i*2,2), 16);
		c = Math.round(Math.min(Math.max(0, c + (c * lum)), 255)).toString(16);
		rgb += ("00"+c).substr(c.length);
	}
	return rgb;
}


// URL DE LA PAGE PHP QUI RECEPTIONNE LES DONNEES
var dataReceiverURL = 'http://leekwars.chocakai.org/report/save.php';

// EDITER dispData POUR CHOISIR LES COLONNES À AFFICHER
//var dispData = ['level', 'turnsPlayed', 'dmg_out', 'dmg_in', 'heal_out', 'heal_in', 'PT', 'PM', 'fails', 'lastHits', 'blabla', 'crashes'];
//var dispData = ['fightId','leekId','name','level','XP','draw','team','alive', 'bonus','gainXP','gainTalent','gainHabs','turnsPlayed','PT','PM',	'actionsWeapon',	'actionsChip','dmg_in','dmg_out','heal_in','heal_out','fails','lastHits','blabla','crashes']; // <--- Toutes les données

var dispData = ['turnsPlayed','actionsWeapon','actionsChip','dmg_in','dmg_out','heal_in','heal_out','shield_in_abs','shield_out_abs','shield_in_rel','shield_out_rel','fails','lastHits']; // <--- Toutes les données


// intitulés des variables
var kikimeterData = {
    'fightId' : 'Fight ID',
    'leekId' :	'Leek ID',
    'teamId' :	'Team ID',
    'compoId':	'Compo ID',
    'name':		'Nom',
    'level' :	'Niveau',
    'XP' :		'XP',
    'draw' :	'Match Nul',
    'team' :	'Équipe',
    'alive' :	'Vivant',
    'bonus' :	'Bonus XP',
    'gainXP' :	'Gain XP',
    'gainTalent':'Gain Talent',
    'gainHabs' :'Gain Habs',
    'turnsPlayed':'Tours joués',
    'PT' :	'PT',
    'PM' :	'PM',
    'actionsWeapon' : 'Tirs',
    'actionsChip' : 'Usages Chips',
    'dmg_in' :	'Dégats reçus',
    'dmg_out' :	'Dégats infligés',
    'heal_in' :	'Soins reçus',
    'heal_out' :'Soins lancés',
    'shield_in_abs' : 'Bouclier absolu reçu',
    'shield_in_rel' : 'Bouclier relatif reçu',
    'shield_out_abs' : 'Bouclier absolu lancé',
    'shield_out_rel' : 'Bouclier relatif lancé',
    'fails' :	'Échecs',
    'lastHits' :'Kills',
    'blabla' :	'Blabla',
    'crashes' : 'Plantages'
} ;

// OBJET LEEK
function Leek(leekId, name, level, XP, team, alive, bonus, gainXP, gainTalent, gainHabs) {
    
    this.data = {} ;
    
    for (var key in kikimeterData) {
        this.data[key] = 0 ;
    }
    var urlTab =  document.URL.split('/');
    this.data['fightId'] = parseInt(urlTab[urlTab.length-1]) ;
    this.data['draw'] = (document.getElementsByTagName('h3')[0].textContent == 'Équipe 1') ? 1 : 0 ;
    this.data['leekId'] = leekId ;
    this.data['name'] = name ;
    this.data['level'] = level ;
    this.data['XP'] = XP ;
    this.data['team'] = team ;
    this.data['alive'] = alive ;
    this.data['bonus'] = bonus ;
    this.data['gainXP'] = gainXP ;
    this.data['gainTalent'] = gainTalent ;
    this.data['gainHabs'] = gainHabs ;
    
    if (teams.length > 0) {
        this.data['teamId'] = (team==1?teams[0].idTeam:teams[1].idTeam);
        this.data['compoId'] = (team==1?teams[0].compo:teams[1].compo);
    }
    
    this.addToData = function(dataName, value) {
        this.data[dataName] += value ;
    } ;
}

// Lecture des teams
function readTeams() {
   	$("#report-general a").each(function(index) {
   		if ($(this)[0].attributes['href'].value.split('/')[1] == 'team'){
   			var teamId = $(this)[0].attributes['href'].value.split('/')[2];
   			
   			var compo=null;
  			/*$.ajax({url: "http://leekwars.com/team/" + teamId}).done(function(data) {
   				$("#leeks div .compo").each(function(index) {
   					compo = $(this).attributes['compo'];
   				});
   			});  */ 			

   			
	   		teams.push({
	   			"idTeam": teamId,
	   			"compo" : compo
	   		});
   		}
   	});
}

// Lit les tableaux d'équipes
function readTables()
{
    var report_tables = document.getElementById('report-general').getElementsByTagName('table') ; 
    var a = true ;
    var team = 0 ;
    
    for (var i = 0; i < report_tables.length; i++) {
        
        if((i+report_tables.length != 4) && (i+report_tables.length != 6))
        {
            team++ ;
            var trs = report_tables[i].children[0].children ;           
            for (var j = 1; j < trs.length; j++) {
                if (trs[j].className != 'total')
                {
                	
                    if (trs[j].children[2].getElementsByClassName('bonus').length ==1)
                    {	var bonus = parseInt(trs[j].children[2].getElementsByClassName('bonus')[0].textContent.replace(/[^\d.]/g, ''))
                    } else
                    {	var bonus = 0 ;
                    }
                    var linkTab = trs[j].getElementsByTagName('a')[0].href.split('/');
                    var leekId = parseInt(linkTab[linkTab.length-1]) ;
                    var name		= trs[j].children[0].textContent ;
                    var alive		=(trs[j].children[0].children[0].className == 'alive') ? 1 : 0 ;
                    var level		= parseInt(trs[j].children[1].textContent.replace(/[^\d.]/g, '')) ;
                    var gainXP		= parseInt(trs[j].children[2].children[1].textContent.replace(/[^\d.]/g, '')) ;
                    var gainTalent	= parseInt(trs[j].children[3].textContent.replace(/[^\d.]/g, '')) ;
                    var gainHabs	= parseInt(trs[j].children[4].textContent.replace(/[^\d.]/g, '')) ;
                    var XP = parseInt(document.getElementById('tt_'+trs[j].children[2].children[0].id).textContent.split('/')[0].replace(/[^\d.]/g, ''));
                    
                    leeks[trs[j].children[0].textContent] = new Leek(leekId, name, level, XP, team, alive, bonus, gainXP, gainTalent, gainHabs) ;
                    a = false ;
                }
            }
        }
    }
}

// Lit la liste des actions
function readActions()
{
    var actions = document.getElementById('actions').children;
    
	var attacker, attackerWeapon, attackerChip;
    
    for(var i=0; i<actions.length; i++) {
                
        // TOUR
        if (/^Tour de ([^\s]+)$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('turnsPlayed', 1) ;
            attacker = null;
            attackerWeapon = null;
            attackerChip = null;
        }
        
        // VARIABLES UTILES POUR LES ACTIONS DE PLUSIEURS LIGNES
        if (/^([^\s]+) tire$/.test(actions[i].textContent)) {
            var attacker = RegExp.$1 ;
            var attackerWeapon = RegExp.$1 ;
            leeks[attacker].addToData('actionsWeapon', 1) ;
        }
        if (/^([^\s]+) lance [^\s]+$/.test(actions[i].textContent)) {
            var attacker = RegExp.$1 ;
            var attackerChip = RegExp.$1 ;
            leeks[attacker].addToData('actionsChip', 1) ;
        }
               
        
        // PT
        if (/^([^\s]+) perd ([0-9]+) PT$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('PT', parseInt(RegExp.$2)) ;
        }
        
        // PM
        if (/^([^\s]+) perd ([0-9]+) PM$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('PM', parseInt(RegExp.$2)) ;
        }
        
        // DEGATS
        if (/^([^\s]+) perd ([0-9]+) PV$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('dmg_in', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
            if (attacker != null) {
	            leeks[attacker].addToData('dmg_out', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
            }
        }
        
        // SOINS
        if (/^([^\s]+) gagne ([0-9]+) PV$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('heal_in', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
            if (attackerChip != null) {
	            leeks[attackerChip].addToData('heal_out', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
            }
        }
        
        // BOUCLIER ABSOLU
        if (/^([^\s]+) gagne ([0-9]+) bouclier absolu$/.test(actions[i].textContent)) {
        	leeks[RegExp.$1].addToData('shield_in_abs', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
        	if (attackerChip != null) {
	            leeks[attackerChip].addToData('shield_out_abs', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
            } 
        }    
        
        // BOUCLIER RELATIF
        if (/^([^\s]+) gagne ([0-9]+) bouclier relatif$/.test(actions[i].textContent)) {
        	leeks[RegExp.$1].addToData('shield_in_rel', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
        	if (attackerChip != null) {
	            leeks[attackerChip].addToData('shield_out_rel', parseInt(RegExp.$2.replace(/[^\d.]/g, ''))) ;
            } 
        }
        
        // ECHEC
        if (/^([^\s]+) tire... Échec !$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('fails', 1) ;
            leeks[RegExp.$1].addToData('actionsWeapon', 1) ;
        }
        if (/^([^\s]+) lance [^\s]+... Échec !$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('fails', 1) ;
            leeks[RegExp.$1].addToData('actionsChip', 1) ;
        }
        
        // MORT
        if (/^([^\s]+) est mort !/.test(actions[i].textContent)) {
            if (attacker != null) {
	            leeks[attacker].addToData('lastHits', 1) ;
            }
        }
        
        // BLABLA
        if (/^([^\s]+) dit : /.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('blabla', 1) ;
        }
        
        // PLANTAGE
        if (/^([^\s]+) a planté !$/.test(actions[i].textContent)) {
            leeks[RegExp.$1].addToData('crashes', 1) ;
        }
    }
}

// Affichage du tableaux pour une team donnée
function displayKikimeterForTeam(team)
{
    var table = document.createElement('table');
    table.className = 'report' ;
    
    var tbody = document.createElement('tbody');
    
    var tr = document.createElement('tr');
    
    var th = document.createElement('th');
    th.appendChild(document.createTextNode('Poireau'));
    tr.appendChild(th) ;
    
    for (var i = 0; i < dispData.length; i++) {
        var th = document.createElement('th');
        th.appendChild(document.createTextNode(kikimeterData[dispData[i]]));
        tr.appendChild(th) ;
    }
    
    tbody.appendChild(tr) ;
    
    for (var j in leeks) {
    	
    	if (leeks[j].data['team'] == team) {
    	
	        tr = document.createElement('tr');
	        
	        td = document.createElement('td');
	        
	        if (leeks[j].data['alive']) {
	            var span = document.createElement('span');
	            span.className = 'alive' ;
	        }
	        else {
	            var span = document.createElement('span');
	            span.className = 'dead' ;
	            td.appendChild(span) ;
	            span = document.createElement('span') ;
	        }
	        
	        var a = document.createElement('a') ;
	        a.href = '/leek/' + leeks[j].data['leekId'] ;
	        a.appendChild(document.createTextNode(leeks[j].data['name'])) ;
	        span.appendChild(a);
	        td.className = 'name';
	        td.appendChild(span) ;
	        
	        tr.appendChild(td) ;
	        
	        for (var i in dispData)	{
	            
	            td = document.createElement('td');
	            td.className = dispData[i] ;
	            
	            td.appendChild(document.createTextNode(leeks[j].data[dispData[i]]));
	            tr.appendChild(td) ;
	        }
	        
	        tbody.appendChild(tr) ;
    	}
    }
    
    table.appendChild(tbody) ;
    
    return table;
    
  }

// Affiche le tableau de résumé
function displayKikimeter()
{
    var tableTeam1 = displayKikimeterForTeam(1);
    var tableTeam2 = displayKikimeterForTeam(2);
    
    var team1 = document.createElement('h3'); 
    team1.appendChild(document.createTextNode('Equipe 1'));
    var team2 = document.createElement('h3'); 
    team2.appendChild(document.createTextNode('Equipe 2'));
    
    var resume = document.createElement('div');
    resume.id = 'report-resume' ;
    
    var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode('Résumé'));
    document.body.appendChild(h1);
    resume.appendChild(h1);
    resume.appendChild(team1);
    resume.appendChild(tableTeam1);
    resume.appendChild(team2);
    resume.appendChild(tableTeam2);
    
    var page=document.getElementById('page');
    page.insertBefore(resume, page.children[3]);
}

// Affiche le graphe des dommages
function displayGraph(donnee) {

	var cpt=0;
	var data = [];
	for (var i in leeks) {
		if (leeks[i].data['team'] == 1) {
			cpt++;
			data.push({
				value: leeks[i].data[donnee],
		        color: colorLuminance(colorTeam1, 0.2*cpt),
		        highlight: colorTeam1,
		        label: leeks[i].data['name']
			});
		}
	}
	cpt=0;
	for (var i in leeks) {
		if (leeks[i].data['team'] == 2) {
			cpt++;
			data.push({
				value: leeks[i].data[donnee],
		        color: colorLuminance(colorTeam2, 0.2*cpt),
		        highlight: colorTeam2,
		        label: leeks[i].data['name']
			});
		}
	}	
	
	var options = {
	    segmentShowStroke : true,
	    segmentStrokeColor : "#fff",
	    segmentStrokeWidth : 2,
	    percentageInnerCutout : 0, 
	    animationSteps : 100,
	    animationEasing : "easeOutBounce",
	    animateRotate : true,
	    animateScale : false
	
	};

	// Ajout du graphe dans le DOM
	var canvas = document.createElement('canvas');
	canvas.id = 'chart_' + donnee;
	canvas.width = '200';
	canvas.height = '200';	

	var td = document.getElementById('td_' + donnee);

	h3 = document.createElement('h3');
	h3.style['text-align'] = 'center';
	h3.style['margin-left'] = '0px';
	h3.appendChild(document.createTextNode(kikimeterData[donnee]));
	td.appendChild(h3);
	td.appendChild(canvas);

	// Chargement du graphe	
	var chartCtx = document.getElementById("chart_" + donnee).getContext("2d");
	var chart = new Chart(chartCtx).Pie(data,options);
}

function displayAllGraphs() {
	var h3, tr, td;
	
	var graphs = document.createElement('div');
	graphs.id = 'graphs';
	var page=document.getElementById('page');
    page.insertBefore(graphs, page.children[4]);
	
	var h1 = document.createElement('h1');
    h1.appendChild(document.createTextNode('Graphes'));
    graphs.appendChild(h1);
    		
	var table = document.createElement('table');
	table.width = "100%";
	table.style['text-align'] = 'center';
	graphs.appendChild(table);
	var tbody = document.createElement('tbody');
	table.appendChild(tbody);
	tr = document.createElement('tr');
	table.appendChild(tr);
	
	// Dommages
	td = document.createElement('td');
	td.width = "25%";
	td.id = "td_dmg_out";
	tr.appendChild(td);
	displayGraph('dmg_out');
	
	// Heals
	td = document.createElement('td');
	td.width = "25%";
	td.id = "td_heal_out";
	tr.appendChild(td);
	displayGraph('heal_out');
	
	// Shield abs
	td = document.createElement('td');
	td.width = "25%";
	td.id = "td_shield_out_abs";
	tr.appendChild(td);
	displayGraph('shield_out_abs');
	
	// Shield abs
	td = document.createElement('td');
	td.width = "25%";
	td.id = "td_shield_out_rel";
	tr.appendChild(td);
	displayGraph('shield_out_rel');		
}



// Truc AJAX pour envoyer les données à la page PHP
function getXMLHttpRequest() {
    var xhr = null;
    
    if (window.XMLHttpRequest || window.ActiveXObject) {
        if (window.ActiveXObject) {
            try {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(e) {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        } else {
            xhr = new XMLHttpRequest(); 
        }
    } else {
        alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
        return null;
    }
    
    return xhr;
}


if (document.URL.indexOf("http://leekwars.com/report", 0) != -1) {
	//		LISTE DES POIREAUX
	var leeks = {} ;
	var teams = []	 ;
	
	//		LECTURE DE TEAMS
	readTeams();
	console.log(teams);
	
	//		LECTURE DES TABLEAUX
	readTables() ;
	
	//		LECTURE DES ACTIONS
	readActions() ;
	
	//		CREATION DU RESUME
	displayKikimeter() ;
	
	//		CREATION DU GRAPHE DAMAGES
	displayAllGraphs() ;
	
	//		CHECK MASQUER LOG
	/*var divCheckLog = document.createElement('div');
	divCheckLog.style['display'] = 'inline';
	var checkLog = document.createElement('input');
	checkLog.type = 'checkbox';
	checkLog.name = 'checkLog';
	checkLog.value = 1;
	divCheckLog.appendChild(document.createTextNode('afficher log'));
	divCheckLog.appendChild(checkLog);
	document.getElementById('page').children[3].appendChild(divCheckLog);*/
	
	
	//		ENVOI DES DONNEES SUR UNE PAGE DISTANTE
	if (dataReceiverURL != '') {
	    var json = 'json=' + JSON.stringify( leeks );	// mise au format JSON
	    
	    $.ajax({
	        type : 'POST',
	        url : dataReceiverURL,
	        dataType : 'json', 
	        data: json
	    }).success(function(data) {
			$('#page h1').first().append('<span class="save ok" title="Sauvegarde effectuée"></span>');
		}).error(function(jqXHR, textStatus) {
			$('#page h1').first().append('<span class="save ko" title="Sauvegarde en erreur"></span>');
		});
	}
	
	// Ajout du filtre
	$('#report-actions h1').append('<input id="filtre" type="text" /><span id="filtre_button" class="button">Filtrer</span>');
	$('#filtre_button').click(function (data) {
		var text = $('#filtre').val();
		
		$('#actions .action').show();
		$('#actions .log').show();

		if ("" != text && null != text) {
			$('#actions .action:not(:contains(' + text + '))').hide();
			$('#actions .log:not(:contains(' + text + '))').hide();

			$('#actions .action .turn').parent().show();
		}
	});
}	